package com.hongyun.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.hongyun.tms.common.PageResponseDto;
import com.hongyun.tms.common.constants.DefaultCreateByConstant;
import com.hongyun.tms.common.constants.DeleteReferenceConstant;
import com.hongyun.tms.common.dto.mcustomer.MCustomerQueryDto;
import com.hongyun.tms.common.dto.mcustomer.MCustomerSaveReqDto;
import com.hongyun.tms.common.dto.tug.SelecSearchDTO;
import com.hongyun.tms.common.utils.MapperingUtils;
import com.hongyun.tms.common.utils.ReferenceCheckUtil;
import com.hongyun.tms.common.vo.MCustomerVO;
import com.hongyun.tms.entity.MCustomer;
import com.hongyun.tms.entity.PordWork;
import com.hongyun.tms.entity.ProdPlan;
import com.hongyun.tms.mapper.MCustomerMapper;
import com.hongyun.tms.service.IMCustomerService;
import com.hongyun.tms.service.IPordWorkService;
import com.hongyun.tms.service.IProdPlanService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 客户信息表 服务实现类
 * </p>
 *
 * @author liPeng
 * @since 2024-06-06
 */
@Service
public class MCustomerServiceImpl extends ServiceImpl<MCustomerMapper, MCustomer> implements IMCustomerService {
    //    @Resource
//    private IRepairBillService billService;
    @Resource
    private IProdPlanService planService;
    @Resource
    private IPordWorkService workService;

    @Override
    public PageResponseDto<MCustomerVO> pageList(MCustomerQueryDto query) {
        Page<MCustomer> page = new Page<>(query.getStartPage(), query.getPageSize());
        baseMapper.selectPage(page, new LambdaQueryWrapper<MCustomer>()
                //身份证
                .eq(StringUtils.isNotBlank(query.getIdNumber()), MCustomer::getIdNumber, query.getCustomerName())
                .eq(!Objects.isNull(query.getType()), MCustomer::getType, query.getType())
                //客户姓名
                .like(StringUtils.isNotBlank(query.getCustomerName()), MCustomer::getCustomerName, query.getCustomerName())
                //联系人姓名
                .like(StringUtils.isNotBlank(query.getContacts()), MCustomer::getContacts, query.getContacts())
                //联系人电话
                .like(StringUtils.isNotBlank(query.getTel()), MCustomer::getTel, query.getTel())
                //地址
                .like(StringUtils.isNotBlank(query.getAddress()), MCustomer::getAddress, query.getAddress())

        );
        return (PageResponseDto<MCustomerVO>) new PageResponseDto(page, MCustomerVO.class);
    }

    @Override
    public List<Map<String, Object>> getCustomerList(SelecSearchDTO selectCommonSearch) {
        return baseMapper.getCustomerList(selectCommonSearch);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> asList) {
        //删除前，校验此员工(或员工list) 有没有被其他菜单引用
        referenceCheck(asList);
        removeByIds(asList);
    }


    private void referenceCheck(List<String> customerIds) {
        //作业计划引用check
        ReferenceCheckUtil.checkReference(planService, ProdPlan::getCustomerId, customerIds, DeleteReferenceConstant.PROD_PLAN_MENU, MCustomer::getCustomerName, id -> getOne(new LambdaQueryWrapper<MCustomer>().eq(MCustomer::getId, id)));
        //作业记录check
        ReferenceCheckUtil.checkReference(workService, PordWork::getCustomerId, customerIds, DeleteReferenceConstant.PORD_WORK_MENU, MCustomer::getCustomerName, id -> getOne(new LambdaQueryWrapper<MCustomer>().eq(MCustomer::getId, id)));
        //修船申请check
//        ReferenceCheckUtil.checkReference(billService, RepairBill::getCustomerId, customerIds, DeleteReferenceConstant.REPAIR_SHIP_MENU, MCustomer::getCustomerName, id -> getOne(new LambdaQueryWrapper<MCustomer>().eq(MCustomer::getId, id)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateCustomer(MCustomerSaveReqDto dto) {
        MCustomer customer = MapperingUtils.copyProperties(dto, MCustomer.class)
                .setUpdateTime(LocalDateTime.now())
        .setUpdateBy(DefaultCreateByConstant.userId)
        .setUpdateByName(DefaultCreateByConstant.userId.toString());

        if (dto.getId() == null) {
            customer.setCreateBy(DefaultCreateByConstant.userId);
            customer.setCreateByName(DefaultCreateByConstant.userId.toString());
            customer.setCreateTime(LocalDateTime.now());
            Long id = IdWorker.getId();
            customer.setId(id);
            customer.setCustomerCode(id.toString());
            save(customer);
        } else {
            updateById(customer);
        }
    }

    /**
     * 导出客户
     *
     * @param query 查询
     * @return allData
     */
    @Override
    public List<MCustomerVO> export(MCustomerQueryDto query) {
        long currentPage = 1;
        List<MCustomerVO> allRecords = Lists.newArrayList();

        while (true) {
            query.setStartPage(currentPage);
            PageResponseDto<MCustomerVO> page = this.pageList(query);
            List<MCustomerVO> records = page.getRecords();
            allRecords.addAll(records);

            if (records.size() < query.getPageSize()) {
                // 当前页的记录数小于 pageSize，说明已经是最后一页
                break;
            }
            currentPage++;
        }

        return allRecords;
    }
}
